from google.appengine.ext import db
from django.core.paginator import ObjectPaginator, InvalidPage

import base
import models

class Main(base.RequestHandler):
    def get(self, *args):
        bugs = models.Bug.all().order("-submitted")
        if self.request.get("fixed", None) is not None:
            bugs.filter("fixed", False)
        query = self.request.get("query", None)
        if query:
            bugs = bugs.search(query)
        bugs = bugs.fetch(limit=100)
        perpage = self.getint("perpage", 10)
        currpage = self.getint("page", 0)
        paginator = ObjectPaginator(bugs, perpage)
        try:
            objs = paginator.get_page(currpage)
        except InvalidPage:
            raise http.Http404
        ret = {
            "bugs": [o.to_dict() for o in objs],
            "perpage": perpage,
            "currpage": currpage,
            "has_next": paginator.has_next_page(currpage),
            "has_previous": paginator.has_previous_page(currpage),
            "next": currpage + 1,
            "previous": currpage - 1
        }
        self.json(ret)